package com.demo.petshop.controller;

import com.demo.petshop.entity.Users;
import com.demo.petshop.service.EmailService;
import com.demo.petshop.service.UsersService;
import com.demo.petshop.service.impl.LoginUser;
import com.demo.petshop.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private EmailService emailService;

    @Autowired
    private UsersService usersService;

    private final Map<String, String> verificationCodes = new HashMap<>();

    @PostMapping("/send-code")
    public Result sendVerificationCode(@RequestParam String email) {
        try {
            String code = generateRandomCode();
            verificationCodes.put(email, code);
            emailService.sendVerificationCode(email, code);
            return Result.success("验证码已发送到邮箱");
        } catch (Exception e) {
            return Result.error(Integer.valueOf("发送验证码失败: " + e.getMessage()));
        }
    }

    private String generateRandomCode() {
        SecureRandom random = new SecureRandom();
        return String.format("%06d", random.nextInt(999999));
    }

    @PostMapping("/verify-code")
    public Result verifyCode(@RequestParam String email, @RequestParam String code, HttpServletResponse response) {
        String storedCode = verificationCodes.get(email);
        
        if (storedCode != null && storedCode.equals(code)) {
            verificationCodes.remove(email); // 验证成功后移除验证码

            // 获取用户信息并设置认证
            Users user = usersService.getUserByEmail(email);
            if (user != null) {
                // 生成JWT token
                String token = com.demo.petshop.util.JwtUtil.generateToken(user);
                
                // 设置认证上下文
                UserDetails userDetails = new LoginUser(user);
                Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, token, userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authentication);
                
                // 将JWT token添加到响应头
                response.setHeader("Authorization", "Bearer " + token);
                
                // 返回完整的用户信息
                Map<String, Object> userData = new HashMap<>();
                userData.put("userId", user.getUserId());
                userData.put("username", user.getUsername());
                userData.put("email", user.getEmail());
                userData.put("phone", user.getPhone());
                userData.put("avatar", user.getAvatar());
                userData.put("bio", user.getBio());
                userData.put("memberLevel", user.getMemberLevel());
                userData.put("createdAt", user.getCreatedAt());
                userData.put("updatedAt", user.getUpdatedAt());
                userData.put("token", token);

                return Result.success(userData);
            } else {
                return Result.fail("用户不存在");
            }
        } else {
            return Result.fail("验证码错误或已过期");
        }
    }

    @PostMapping("/login")
    public Result loginByEmail(@RequestParam String email, @RequestParam String password) {
        Users user = usersService.loginByEmail(email, password);
        if (user != null) {
            return Result.success("登录成功");
        } else {
            return Result.fail("登录失败，邮箱或密码错误");
        }
    }
}
